Briefly tell me how we create custom Html Helper in asp.net MVC with an example as well as an image.
How we create custom HTML Helper in Asp.net MVC?
41503-Feb-2020
Updated on 03-Feb-2020
Home / DeveloperSection / Forums / How we create custom HTML Helper in Asp.net MVC?
Briefly tell me how we create custom Html Helper in asp.net MVC with an example as well as an image.
Nishi Tiwari
03-Feb-2020Mainly there are 2 ways to create custom HTML helper in asp.net MVC.
In the example, we will create an HTML helper method that will create a marked HTML span with color and font settings for span in it. For that, we will create a folder with the name “Custom_Helpers” inside that we add a static class with name “LabelborderHelper”
Creating Custom HTML Helper in Asp.Net MVC using Static Method
In this type of HTML helper, we will take text as input and add font size, color, the weight of span text for which we need to write code like below:-
We will now add a controller and give a name to it as “TesthelperController” which will be shown below
Lastly, we will add a view for the above controller to test a custom helper method for which right-click on the controller select Add View. Once we add View open Index.cshtml file and write the code for this shown below
When we create view run application to see the output which will be shown below:-
Creating Custom HTML Helper in Asp.Net MVC using Extension Method
If we will create an extension method then it will be available in the helper method of the view.
E.g. @Html.LabelBorderExtension. We will create an extension method class with name “LabelborderExtensionhelper” in the folder “Custom_Helpers” and write the code for it
We will now add the view for the above controller to test the custom helper method for which we just right click on controller select Add View. Once we add View open file Index.cshtml and write the code like as shown below
The extension method output will be shown like below
Using both static and extension methods in asp.net MVC you can create custom HTML helpers in a simple way.